﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MyMoviesBrowserLibrary;
using System.IO;
using System.Net;

namespace TVManager
{
    /// <summary>
    /// Interaction logic for SeasonWindow.xaml
    /// </summary>
    public partial class SeasonWindow : Window
    {
        private TVManagerBusinessLayer bl = new TVManagerBusinessLayer();
        public Season Season
        {
            get { return DataContext as Season; }
            set
            {
                DataContext = value;
                if (value == null)
                    return;

                seasonTitle.Text = string.Format("{0} Season {1}", value.Series.SeriesName, value.SeasonNumber);
                value.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(value_PropertyChanged);
                LoadImages();
                LoadEpisodes();
            }
        }

        void value_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            bl.WatchSeason(Season);
        }
        public SeasonWindow()
        {
            InitializeComponent();
            chooseSeasonImageButton.Click += new RoutedEventHandler(chooseSeasonImageButton_Click);
            episodesListBox.SelectionChanged += new SelectionChangedEventHandler(episodesListBox_SelectionChanged);
            displayEpisodesCheckbox.Click += new RoutedEventHandler(displayEpisodesCheckbox_Click);

            displayEpisodesCheckbox.IsChecked = Settings.Default.HideEpisodesWithoutFiles;

            seriesGrid.Drop += new DragEventHandler(rootLayout_Drop);
            bl.AddFilesToSeriesCompleted += new AddFilesToSeriesEvent(bl_AddFilesToSeriesCompleted);
        }

        void bl_AddFilesToSeriesCompleted(List<Episode> episodes)
        {
            episodes.RemoveAll(ep => ep == null);
            foreach (Episode episode in episodes)
            {
                Episode ep = Season.Episodes.SingleOrDefault(e2 => e2.EpisodeId == episode.EpisodeId);
                if (ep != null)
                    ep.FileLocation = episode.FileLocation;
            }
            LoadEpisodes();
            statusControl.Hide();
        }

        void rootLayout_Drop(object sender, DragEventArgs e)
        {
            if (e.Data is System.Windows.DataObject && ((System.Windows.DataObject)e.Data).ContainsFileDropList())
            {
                statusControl.StatusText = "Adding File(s)";
                statusControl.Show();
                List<string> filenames = new List<string>();
                foreach (string filename in ((System.Windows.DataObject)e.Data).GetFileDropList())
                    filenames.Add(filename);
                bl.AddFilesToSeriesAsync(filenames, Season.SeriesId, Season.SeasonNumber);                                                           
            }
        }

        void displayEpisodesCheckbox_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.HideEpisodesWithoutFiles = displayEpisodesCheckbox.IsChecked.Value;
            Settings.Default.Save();
            LoadEpisodes();
        }

        void episodesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Episode episode = episodesListBox.SelectedValue as Episode;
            if (episode != null)
                episodeControl.Episode = episode;
        }

        void chooseSeasonImageButton_Click(object sender, RoutedEventArgs e)
        {
            ChooseImageWindow chooseImageWindow = new ChooseImageWindow();
            chooseImageWindow.Series = Season.Series;
            chooseImageWindow.BannerType = "season";
            chooseImageWindow.SeasonNumber = Season.SeasonNumber;
            chooseImageWindow.BannerSelected += new BannerSelectedEvent(chooseImageWindow_BannerSelected);
            chooseImageWindow.ShowDialog();
        }

        void chooseImageWindow_BannerSelected(object sender, string bannerUrl, string bannerType)
        {
            statusControl.Show();
            statusControl.StatusText = "Retrieving Image";
            string fileLocation = System.IO.Path.Combine(Season.Series.FolderLocation, string.Format("Season {0}\\folder.jpg", Season.SeasonNumber));
            seasonImage.Source = null;

            DirectoryInfo dir = new DirectoryInfo(System.IO.Path.GetDirectoryName(fileLocation));
            if (!dir.Exists)
                dir.Create();

            WebClient client = new WebClient();
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            statusControl.StatusProgressBar.IsIndeterminate = false;
            client.DownloadFileAsync(new Uri(bannerUrl), fileLocation);

        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            statusControl.StatusProgressBar.Value = e.ProgressPercentage;
        }

        void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("There was an error downloading image.");
            }
            else
                LoadImages();
            statusControl.Hide();
        }

        private void LoadImages()
        {
            if (Season == null)
                return;
            
            if (File.Exists(Season.ImageLocation))
            {
                //Uri uri = new Uri("file://" +bannerFile, UriKind.RelativeOrAbsolute);
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(Season.ImageLocation));
                bitmap.EndInit();
                seasonImage.Source = bitmap;
            }
        }

        private void LoadEpisodes()
        {
            episodesListBox.ItemsSource = Season.Episodes.Where(e => !displayEpisodesCheckbox.IsChecked.Value ||
                (displayEpisodesCheckbox.IsChecked.Value && !string.IsNullOrEmpty(e.FileLocation))).OrderBy(e => e.EpisodeNumber);
        }
    }
}
